<!doctype html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <title>教学视频语音提取文本系统</title>
  <style>
    /*移除链接默认下划线*/
      .task-section a{
      text-decoration: none;
      }
    /* 全局重置与基础样式 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: "Microsoft YaHei", Arial, sans-serif;
    }

    /* 视频背景容器 */
    .background-container {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      overflow: hidden;
      background-color: #000; /* 视频加载前显示黑色 */
    }

    /* 背景视频样式 */
    .background-video {
      position: absolute;
      top: 50%;
      left: 50%;
      min-width: 100%;
      min-height: 100%;
      width: auto;
      height: auto;
      transform: translate(-50%, -50%);
      filter: brightness(0.6); /* 保持原亮度效果 */
      opacity: 0; /* 初始透明，加载完成后显示 */
      transition: opacity 0.5s ease-in-out;
    }

    /* 视频加载完成后显示 */
    .background-video.loaded {
      opacity: 1;
    }

    body {
      background-color: transparent;
      color: #333;
      position: relative;
      padding-bottom: 60px;
      transition: background-color 0.3s, color 0.3s;
      /* 添加导航栏高度的内边距，避免内容被遮挡 */
      padding-top: 60px;
    }

    /* 顶部导航栏 */
    .top-nav {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 20px;
      background: rgba(255, 255, 255, 0.9);
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
      transition: background-color 0.3s;
      /* 添加以下两行代码 */
      position: fixed; /* 固定定位 */
      width: 100%; /* 宽度占满整个屏幕 */
      top: 0; /* 固定在顶部 */
      z-index: 1000; /* 确保在其他内容上方 */
    }

    .top-nav .logo {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }

    .top-nav .user-area {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .top-nav .user-area span {
      color: #666;
    }

    .logout-btn, .profile-btn {
      padding: 6px 14px;
      background-color: #ff6347;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
    }

    .profile-btn {
      background-color: #4a86e8;
      margin-right: 10px;
    }

    .profile-btn:hover {
      background-color: #3a76d8;
    }

    .logout-btn:hover {
      background-color: #e55236;
    }

    /* 返回按钮 */
    .back-btn {
      padding: 6px 14px;
      background-color: #50d8e0;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.2s;
      margin-right: 10px;
    }

    .back-btn:hover {
      background-color: #40bec7;
    }

    /* 主容器：操作区 + 任务列表 */
    .container {
      max-width: 1200px;
      margin: 20px auto;
      padding: 0 20px;
    }

    /* 操作区：上传 + 模型语言选择 + 按钮 */
    .operation-section {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 24px;
      padding: 24px;
      background: rgba(193, 240, 240, 0.5);
      border-radius: 8px;
      margin-bottom: 20px;
    }

    .upload-box {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 120px;
      height: 120px;
      border: 2px dashed #999;
      border-radius: 8px;
      background: rgba(232, 248, 248, 0.5);
      color: #666;
      cursor: pointer;
      transition: all 0.2s;
    }

    .upload-box:hover {
      border-color: #666;
      background: rgba(240, 252, 252, 0.5);
    }

    .upload-box img {
      width: 32px;
      margin-bottom: 8px;
    }

    #video {
      display: none;
    }

    .file-info {
      text-align: center;
      margin-top: 4px;
      font-size: 12px;
      color: #999;
      width: 100%;
    }

    .file-info-row {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    /* 模型、语言选择容器 */
    .select-group {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .select-group label {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }

    .select-group select {
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
      width: 200px;
      cursor: pointer;
      background: rgba(255, 255, 255, 0.5);
    }

    /* 开始提取按钮 */
    .start-btn {
      margin-left: auto;
      padding: 10px 24px;
      background: #50d8e0;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background 0.2s;
    }

    .start-btn:hover {
      background: #40bec7;
    }

    /* 提示消息 */
    .flash-messages {
      color: #d9534f;
      margin: 10px 20px;
    }

    /* 任务列表 */
    .task-section {
      background: rgba(255, 255, 255, 0.7);
      border-radius: 8px;
      padding: 24px;
    }

    .task-section h3 {
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
    }

    .task-table {
      width: 100%;
      border-collapse: collapse;
    }

    .task-table th,
    .task-table td {
      padding: 12px 8px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    .task-table th {
      background: rgba(248, 249, 250, 0.75);
      font-weight: 500;
    }

    .status-processing {
      color: #f0ad4e;
    }

    .status-completed {
      color: #5cb85c;
    }

    .status-failed {
      color: #d9534f;
    }

    .action-btn {
      padding: 4px 8px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      margin-right: 5px;
    }

    .download-btn {
      background-color: #5cb85c;
      color: white;
    }

    .clean-btn {
      background-color: #f0ad4e;
      color: white;
    }

    /* 底部固定黑框 */
    .footer {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      background: rgba(51, 51, 51, 0.9);
      color: #fff;
      text-align: center;
      padding: 12px 0;
      font-size: 12px;
    }
  </style>
  <style>
  /* 深色模式样式 */
  body.dark-mode {
    background-color: #121212;
    color: #e0e0e0;
  }

  body.dark-mode .top-nav {
    background: rgba(30, 30, 30, 0.9);
  }

  /* 深色模式下导航栏文字颜色改为白色 */
  body.dark-mode .top-nav .logo,
  body.dark-mode .top-nav .user-area span {
    color: white;
  }

  body.dark-mode .operation-section {
    background: rgba(40, 40, 40, 0.5);
  }

  body.dark-mode .upload-box {
    background: rgba(50, 50, 50, 0.7);
    border-color: #505050;
  }

  body.dark-mode .upload-box img {
    filter: invert(1); /* 反色处理，使图标变白 */
  }

  body.dark-mode .file-info {
    color: #b0b0b0;
  }

  body.dark-mode .select-group label {
    color: #ffffff;
  }

  body.dark-mode .select-group select {
    background: rgba(50, 50, 50, 0.7);
    color: #e0e0e0;
    border-color: #505050;
  }

  /* 保持开始提取按钮原有样式不变 */
  body.dark-mode .start-btn {
    background: #50d8e0;
    color: #fff;
  }

  body.dark-mode .start-btn:hover {
    background: #40bec7;
  }

  body.dark-mode .task-section {
    background: rgba(30, 30, 30, 0.7);
  }

  body.dark-mode .task-table th,
  body.dark-mode .task-table td {
    background: rgba(40, 40, 40, 0.5);
    color: #e0e0e0;
    border-color: #505050;
  }

  body.dark-mode .action-btn {
    background-color: #4a4a4a;
    color: #e0e0e0;
  }

  body.dark-mode .download-btn {
    background-color: #4caf50;
    color: #e0e0e0;
  }

  body.dark-mode .clean-btn {
    background-color: #ff9800;
    color: #e0e0e0;
  }

  body.dark-mode .flash-messages {
    color: #ff9800;
  }
</style>
</head>

<body>
  <!-- 视频背景容器 -->
  <div class="background-container">
    <video class="background-video" autoplay muted loop playsinline>
      <!-- 替换为你的视频路径 -->
      <source src="/static/videos/c1.mp4" type="video/mp4">
      <!-- 可选：添加其他格式作为 fallback -->
      <source src="/static/videos/background.webm" type="video/webm">
      <!-- 如果浏览器不支持视频，则显示此文本 -->
      您的浏览器不支持视频背景
    </video>
  </div>

  <!-- 顶部导航 -->
  <div class="top-nav">
    <div class="logo">TEFS</div>
    <div class="user-area">
        <a href="{{ url_for('features') }}">
            <button class="back-btn">返回功能页</button>
        </a>
        <span>用户</span>
        <span>{{ username }}</span>
        <a href="{{ url_for('profile') }}">
            <button class="profile-btn">账户设置</button>
        </a>
        <a href="{{ url_for('logout') }}">
            <button class="logout-btn">登出</button>
        </a>
        <button id="theme-toggle" style="margin-left: 10px; padding: 6px 12px; background-color: #4a86e8; color: white; border: none; border-radius: 4px; cursor: pointer;">切换深色模式</button>
    </div>
</div>

  <!-- 主容器 -->
  <div class="container">
    <!-- 操作区 -->
    <form id="upload-form" class="operation-section">
      <!-- 上传区域 -->
      <label class="upload-box" for="video">
        <img src="https://cdn-icons-png.flaticon.com/512/1383/1383657.png" alt="加号">
        <span>点击上传视频</span>
        <input type="file" name="video" id="video" accept="video/*" required>
      </label>
      <div class="file-info" id="file-info">未选择文件</div>

      <!-- 模型选择 -->
      <div class="select-group">
        <label for="model">模型选择：</label>
        <select name="model" id="model">
          {% for model in models %}
          <option value="{{ model }}" {% if model=="small" %}selected{% endif %}>
            {{ model }}
          </option>
          {% endfor %}
        </select>
      </div>

      <!-- 语言选择 -->
      <div class="select-group">
        <label for="language">语言选择：</label>
        <select name="language" id="language">
          {% for code, name in languages.items() %}
          <option value="{{ code }}">{{ name }}</option>
          {% endfor %}
        </select>
      </div>

      <!-- 开始提取按钮 -->
      <button type="submit" class="start-btn">开始提取</button>
    </form>

    <!-- 提示消息 -->
    {% with messages = get_flashed_messages() %}
    {% if messages %}
    <div class="flash-messages">
      <ul>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
      </ul>
    </div>
    {% endif %}
    {% endwith %}

    <!-- 任务列表（历史记录） -->
    <div class="task-section">
      <h3>历史记录</h3>
      {% if tasks %}
      <table class="task-table">
        <thead>
          <tr>
            <th>文件名</th>
            <th>模型</th>
            <th>语言</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>完成时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {% for task in tasks %}
          <tr>
            <td>
              {% set max_length = 30 %}  <!-- 可根据需要调整最大显示长度 -->
              {% if task.original_name|length > max_length %}
                {{ task.original_name[:max_length] }}...
              {% else %}
                {{ task.original_name }}
              {% endif %}
            </td>
            <td>{{ task.model_name }}</td>
            <td>{{ languages.get(task.language, task.language) }}</td>
            <td class="status-{{ task.status }}">
              {% if task.status == 'processing' %}处理中{% endif %}
              {% if task.status == 'completed' %}已完成{% endif %}
              {% if task.status == 'failed' %}失败{% endif %}
            </td>
            <td>{{ task.created_at }}</td>
            <td>{{ task.completed_at if task.completed_at else '-' }}</td>
            <td>
              {% if task.status == 'completed' %}
                <a href="{{ url_for('download', filename=task.txt_name) }}">
                  <button class="action-btn download-btn">下载</button>
                </a>
                {% if not task.cleaned %}
                <a href="{{ url_for('clean_task', task_id=task.id) }}">
                  <button class="action-btn clean-btn">去杂</button>
                </a>
                {% else %}
                <span style="color: #5cb85c;">已去杂</span>
                {% endif %}
              {% endif %}
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
      {% else %}
      <p>暂无任务记录</p>
      {% endif %}
    </div>
  </div>

  <!-- 底部固定黑框 -->
  <div class="footer">
    产品由句号团队开发
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
        // --- THEME AND VIDEO BACKGROUND LOGIC (Unchanged) ---
        const theme = localStorage.getItem('theme');
        if (theme === 'dark') {
            document.body.classList.add('dark-mode');
            document.getElementById('theme-toggle').textContent = '切换浅色模式';
        }
        const backgroundVideo = document.querySelector('.background-video');
        backgroundVideo.addEventListener('loadeddata', () => backgroundVideo.classList.add('loaded'));
        setTimeout(() => !backgroundVideo.classList.contains('loaded') && backgroundVideo.classList.add('loaded'), 3000);

        const fileInput = document.getElementById('video');
        const fileInfo = document.getElementById('file-info');
        fileInput.addEventListener('change', () => {
            fileInfo.textContent = fileInput.files.length > 0 ? `已选择：${fileInput.files[0].name}` : '未选择文件';
        });

        // --- THEME TOGGLE (Unchanged) ---
        document.getElementById('theme-toggle').addEventListener('click', function() {
            const body = document.body;
            body.classList.toggle('dark-mode');
            if (body.classList.contains('dark-mode')) {
                this.textContent = '切换浅色模式';
                localStorage.setItem('theme', 'dark');
            } else {
                this.textContent = '切换深色模式';
                localStorage.setItem('theme', 'light');
            }
        });

        // --- NEW: AJAX FORM SUBMISSION ---
        document.getElementById('upload-form').addEventListener('submit', async function(e) {
            e.preventDefault(); // Prevent the default page reload

            const form = e.target;
            const formData = new FormData(form);
            const videoFile = form.querySelector('#video').files[0];
            const btn = form.querySelector('.start-btn');

            if (!videoFile) {
                alert('请选择视频文件');
                return;
            }

            const originalBtnText = btn.textContent;
            btn.textContent = '上传中...';
            btn.disabled = true;

            try {
                const response = await fetch("{{ url_for('upload') }}", {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();

                if (result.success) {
                    createAndInsertTranscriptionProgressTask(result.task_id, videoFile.name, formData.get('model'), formData.get('language'));
                    startTranscriptionProgressPolling(result.task_id);
                } else {
                    alert('任务提交失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                alert('请求失败: ' + error);
            } finally {
                btn.textContent = originalBtnText;
                btn.disabled = false;
            }
        });
    });

    function createAndInsertTranscriptionProgressTask(taskId, fileName, model, lang) {
        const tableBody = document.querySelector('.task-table tbody');
        if (!tableBody) return;

        // Use a JS object for language mapping, passed from Flask
        const langMap = {{ languages|tojson }};
        const langName = langMap[lang] || lang;

        const newRowHTML = `
            <tr id="task-item-progress-${taskId}">
              <td>${fileName.length > 30 ? fileName.substring(0, 30) + '...' : fileName}</td>
              <td>${model}</td>
              <td>${langName}</td>
              <td class="status-processing" id="progress-status-${taskId}">准备中...</td>
              <td colspan="2">
                  <div style="background-color:#e9ecef; border-radius:4px; height:20px; overflow:hidden;">
                    <div id="progress-bar-${taskId}" style="width:0%; height:100%; background-color:#f0ad4e; transition:width 0.4s ease;"></div>
                  </div>
              </td>
              <td id="progress-text-${taskId}" style="font-weight:bold; text-align:center;">0%</td>
            </tr>
        `;
        // Insert the new row at the very top of the table body
        tableBody.insertAdjacentHTML('afterbegin', newRowHTML);
    }
    function startTranscriptionProgressPolling(taskId) {
    const progressBar = document.getElementById(`progress-bar-${taskId}`);
    const progressText = document.getElementById(`progress-text-${taskId}`);
    const statusText = document.getElementById(`progress-status-${taskId}`);
    let hasProgressed = false; // 标记是否已经有过进度（超过0%）

    const interval = setInterval(async () => {
        try {
            const response = await fetch(`/transcription_progress/${taskId}`);
            if (!response.ok) {
                clearInterval(interval);
                location.reload();
                return;
            }

            const data = await response.json();
            const progressNum = data.progress; // 数字类型用于判断
            const progress = progressNum.toFixed(1); // 格式化用于显示

            // 核心逻辑：如果检测到0%且之前有过进度，则刷新
            if (progressNum <= 0 && hasProgressed) {
                clearInterval(interval);
                location.reload(); // 刷新页面
                return;
            }

            // 记录进度已经超过0%的状态
            if (progressNum > 0) {
                hasProgressed = true;
            }

            progressBar.style.width = `${progress}%`;
            progressText.textContent = `${progress}%`;

            // 更新状态文本
            if (progressNum > 50) {
                statusText.textContent = '转写中...';
            } else if (progressNum > 0) {
                statusText.textContent = '提取音频...';
            }

            // 处理完成状态
            if (progressNum >= 100) {
                progressText.textContent = '100%';
                statusText.textContent = '已完成!';
                progressBar.style.backgroundColor = '#5cb85c';
                clearInterval(interval); // 完成后停止轮询
            }
        } catch (error) {
            console.error('Progress polling failed:', error);
            clearInterval(interval);
            progressText.textContent = '错误';
        }
    }, 1000); // 1秒轮询一次
}

</script>
</body>
</html>
